package com.example.teatea.controller;

import com.example.teatea.SeatMoreApp;
import com.example.teatea.dao.*;
import com.example.teatea.project.Good;
import com.example.teatea.project.Member;
import com.example.teatea.project.Staff;
import com.example.teatea.tools.GetTime;
import com.example.teatea.tools.ListTools;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;

public class MainController implements Initializable {

    public Button returnBt;
    public Tab staffTab;
    public Button changeStaffBt;
    public Button deleteStaffBt;
    public Tab memberTab;
    public Button addMemberBt;
    public Button changeMemberBt;
    public Button deleteMemberBt;
    public Tab registerTab;
    public Button agreeBt;
    public Button refuseBt;
    public Tab stockTab;
    public Button addGoodBt;
    public Button changeGoodBt;
    public Button deleteGoodBt;
    public Button findStaffBt;
    public TableView staffView;
    public TableColumn staffName;
    public TableColumn staffPhone;
    public TableColumn staffTime;
    public TableColumn staffSex;
    public Button findMemberBt;
    public TableView memberView;
    public TableColumn memberName;
    public TableColumn memberPhone;
    public TableColumn memberTime;
    public TableColumn memberSex;
    public TableColumn memberBirth;
    public TableView registerView;
    public TableColumn registerName;
    public TableColumn registerPhone;
    public TableColumn registerSex;
    public Button findGoodBt;
    public TableView goodView;
    public TableColumn goodName;
    public TableColumn goodType;
    public TableColumn goodPrice;
    public TableColumn goodNum;
    public TableColumn goodImage;
    public static Staff s;
    public static Member m;
    public static Good g;

    private interface Task {
        void execute();
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        loadStaffDate();//默认显示员工表
        loadMemberDate();;//显示会员表
        loadRegisterDate();//显示注册信息表
        loadGoodDate();//显示商品表
        //设置标签与表对应
        setTabVisible(staffTab,staffView);
        setTabVisible(memberTab,memberView);
        setTabVisible(registerTab,registerView);
        setTabVisible(stockTab,goodView);
        ControllerManager.controllerMap.put("main",this);
    }
    
    private void setTabVisible(Tab tab, TableView tableView){
        setTabAction(tab, new Task() {
            @Override
            public void execute() {
                if(tableView.equals(staffView)){
                    memberView.setVisible(false);
                    staffView.setVisible(true);
                    goodView.setVisible(false);
                    registerView.setVisible(false);
                }
                else if(tableView.equals(memberView)){
                    staffView.setVisible(false);
                    memberView.setVisible(true);
                    goodView.setVisible(false);
                    registerView.setVisible(false);
                }
                else if(tableView.equals(goodView)){
                    staffView.setVisible(false);
                    memberView.setVisible(false);
                    goodView.setVisible(true);
                    registerView.setVisible(false);
                }
                else if(tableView.equals(registerView)){
                    staffView.setVisible(false);
                    memberView.setVisible(false);
                    goodView.setVisible(false);
                    registerView.setVisible(true);
                }
            }
        });
    }

    private void setTabAction(Tab tab, Task task) {
        tab.selectedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                task.execute();
            }
        });
    }

    //加载指定数据到员工表
    public void loadStaffDate(){
        //设置每一列的值
        staffName.setCellValueFactory(new PropertyValueFactory<>("sName"));
        staffSex.setCellValueFactory(new PropertyValueFactory<>("sSex"));
        staffPhone.setCellValueFactory(new PropertyValueFactory<>("sPhone"));
        staffTime.setCellValueFactory(new PropertyValueFactory<>("sTime"));
        //调用自定义工具类，得到指定页数据集合
        List<Staff> subList= new FindAll().getAllStaff();
        //设置数据表格的数据源为上述分页集合
        ObservableList<Staff> data = FXCollections.observableArrayList();
        for(Staff staff : subList){
            data.add(staff);
        }
        // 绑定TableView（tbStudent）的数据源
        staffView.setItems(data);
    }

    //加载指定数据到会员表
    public void loadMemberDate(){
        //设置每一列的值
        memberName.setCellValueFactory(new PropertyValueFactory<>("mName"));
        memberSex.setCellValueFactory(new PropertyValueFactory<>("mSex"));
        memberPhone.setCellValueFactory(new PropertyValueFactory<>("mPhone"));
        memberBirth.setCellValueFactory(new PropertyValueFactory<>("mBirthday"));
        memberTime.setCellValueFactory(new PropertyValueFactory<>("mTime"));
        //调用自定义工具类，得到指定页数据集合
        List<Member> subList= new FindAll().getAllMember();
        //设置数据表格的数据源为上述分页集合
        ObservableList<Member> data = FXCollections.observableArrayList();
        for(Member member : subList){
            data.add(member);
        }
        // 绑定TableView（tbStudent）的数据源
        memberView.setItems(data);
    }

    //加载指定数据到注册请求表
    private void loadRegisterDate(){
        //设置每一列的值
        registerName.setCellValueFactory(new PropertyValueFactory<>("sName"));
        registerSex.setCellValueFactory(new PropertyValueFactory<>("sSex"));
        registerPhone.setCellValueFactory(new PropertyValueFactory<>("sPhone"));
        //调用自定义工具类，得到指定页数据集合
        List<Staff> subList= new FindAll().getRegisterStaff();
        //设置数据表格的数据源为上述分页集合
        ObservableList<Staff> data = FXCollections.observableArrayList();
        for(Staff staff : subList){
            data.add(staff);
        }
        // 绑定TableView（tbStudent）的数据源
        registerView.setItems(data);
    }

    //刷新显示商品表
    public void loadGoodDate(){
        //设置每一列的值
        goodName.setCellValueFactory(new PropertyValueFactory<>("gName"));
        goodPrice.setCellValueFactory(new PropertyValueFactory<>("gPrice"));
        goodNum.setCellValueFactory(new PropertyValueFactory<>("gNumber"));
        goodType.setCellValueFactory(new PropertyValueFactory<>("gType"));
        goodImage.setCellValueFactory(new PropertyValueFactory<>("gImage"));
        //调用自定义工具类，得到指定页数据集合
        List<Good> subList= new FindAll().getAllGoods();
        //设置数据表格的数据源为上述分页集合
        ObservableList<Good> data = FXCollections.observableArrayList();
        for(Good good : subList){
            data.add(good);
        }
        // 设置自定义组件，用于显示图片
        goodImage.setCellFactory(new Callback<TableColumn<Staff,String>, TableCell<Staff, String>>() {
            @Override
            public TableCell<Staff, String> call(TableColumn<Staff, String> stuInfoStringTableColumn) {
                TableCell<Staff, String> cell = new TableCell<Staff, String>(){
                    @Override
                    protected void updateItem(String s, boolean b) {//s为单元格的值
                        super.updateItem(s, b);
                        if (b == false && s != null) {
                            HBox box = new HBox();
                            box.setAlignment(Pos.CENTER);
                            File file = new File("E:\\TeaTea\\src\\main\\resources\\com\\example\\teatea\\photo\\food\\" + s);
                            Image img=new Image(file.toURI().toString());//设置图片
                            ImageView imageView=new ImageView(img);
                            imageView.setFitWidth(32);
                            imageView.setFitHeight(32);
                            box.getChildren().add(imageView);
                            this.setGraphic(box);
                        }
                    }
                };
                return cell;
            }
        });
        // 绑定TableView（tbStudent）的数据源
        goodView.setItems(data);
    }

    public void toReturn(ActionEvent actionEvent) throws Exception {
        Stage stage = (Stage) returnBt.getScene().getWindow();
        stage.close();
        SeatMoreApp seatMoreApp = new SeatMoreApp();
        seatMoreApp.start(stage);
    }

    public void toChangeStaff(ActionEvent actionEvent) throws IOException {
        s = (Staff) staffView.getSelectionModel().getSelectedItem();
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/example/teatea/fxml/ChangeStaff.fxml"));
        Scene scene = new Scene(fxmlLoader.load());
        Stage stage = new Stage();
        stage.setScene(scene);
        //设置窗口标题
        stage.setTitle("修改员工信息");
        //设置窗体不关闭不能使用其它窗体
        stage.initModality(Modality.APPLICATION_MODAL);
        //设置窗口大小不能改变
        stage.setResizable(false);
        stage.show();
    }

    public void toDeleteStaff(ActionEvent actionEvent) {
        s = (Staff) staffView.getSelectionModel().getSelectedItem();
        //使用系统确认框询问
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText("您确定要删除员工" + s.getsName() + "的全部信息吗？");
        // 显示对话框，并等待按钮返回
        Optional<ButtonType> result = alert.showAndWait();
        // 判断返回的按钮类型是确定还是取消，再据此分别进一步处理
        if (result.get() == ButtonType.OK) { // 单击了确定按钮OK
            new DeleteStaff().deleteStaff(s.getsName());
            loadStaffDate();//重新加载视图数据
        }
    }

    public void toAddMember(ActionEvent actionEvent) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/example/teatea/fxml/AddMember.fxml"));//定位界面文件
        Scene scene = new Scene(fxmlLoader.load());//加载界面到Scene场景对象
        Stage stage = new Stage();//创建Stage窗体对象
        stage.setScene(scene);//设置窗体的场景
        // stage.initStyle(StageStyle.TRANSPARENT);
        //设置窗口标题
        stage.setTitle("添加会员");
        //设置窗体不关闭不能使用其它窗体
        stage.initModality(Modality.APPLICATION_MODAL);
        //设置窗口大小不能改变
        stage.setResizable(false);
        stage.show();//显示窗体
    }

    public void toChangeMember(ActionEvent actionEvent) throws IOException {
        m = (Member) memberView.getSelectionModel().getSelectedItem();
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/example/teatea/fxml/ChangeMember.fxml"));
        Scene scene = new Scene(fxmlLoader.load());
        Stage stage = new Stage();
        stage.setScene(scene);
        //设置窗口标题
        stage.setTitle("修改会员信息");
        //设置窗体不关闭不能使用其它窗体
        stage.initModality(Modality.APPLICATION_MODAL);
        //设置窗口大小不能改变
        stage.setResizable(false);
        stage.show();
    }

    public void toDeleteMember(ActionEvent actionEvent) {
        m = (Member) memberView.getSelectionModel().getSelectedItem();
        //使用系统确认框询问
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText("您确定要删除会员" + m.getmName() + "的全部信息吗？");
        // 显示对话框，并等待按钮返回
        Optional<ButtonType> result = alert.showAndWait();
        // 判断返回的按钮类型是确定还是取消，再据此分别进一步处理
        if (result.get() == ButtonType.OK) { // 单击了确定按钮OK
            new DeleteMember().deleteMember(m);
            loadMemberDate();//重新加载视图数据
        }
    }

    public void toAgree(ActionEvent actionEvent) {
        s = (Staff) registerView.getSelectionModel().getSelectedItem();
        //使用系统确认框询问
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText("您确定要录入员工" + s.getsName() + "吗？");
        // 显示对话框，并等待按钮返回
        Optional<ButtonType> result = alert.showAndWait();
        // 判断返回的按钮类型是确定还是取消，再据此分别进一步处理
        if (result.get() == ButtonType.OK) { // 单击了确定按钮OK
            s.setsTime(new GetTime().getTime());
            s.setsState(1);
            new AgreeRegister().agreeRegister(s);
            loadRegisterDate();//重新加载视图数据
            loadStaffDate();
        }
    }

    public void toRefuse(ActionEvent actionEvent) {
        s = (Staff) registerView.getSelectionModel().getSelectedItem();
        //使用系统确认框询问
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText("您确定要拒绝员工" + s.getsName() + "的注册请求吗？");
        // 显示对话框，并等待按钮返回
        Optional<ButtonType> result = alert.showAndWait();
        // 判断返回的按钮类型是确定还是取消，再据此分别进一步处理
        if (result.get() == ButtonType.OK) { // 单击了确定按钮OK
            new RefuseRegister().refuseRegister(s);
            loadRegisterDate();//重新加载视图数据
        }
    }

    public void toAddGood(ActionEvent actionEvent) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/example/teatea/fxml/AddGood.fxml"));//定位界面文件
        Scene scene = new Scene(fxmlLoader.load());//加载界面到Scene场景对象
        Stage stage = new Stage();//创建Stage窗体对象
        stage.setScene(scene);//设置窗体的场景
        // stage.initStyle(StageStyle.TRANSPARENT);
        //设置窗口标题
        stage.setTitle("添加商品");
        //设置窗体不关闭不能使用其它窗体
        stage.initModality(Modality.APPLICATION_MODAL);
        //设置窗口大小不能改变
        stage.setResizable(false);
        stage.show();//显示窗体
    }

    public void toChangeGood(ActionEvent actionEvent) throws IOException {
        g = (Good) goodView.getSelectionModel().getSelectedItem();
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/example/teatea/fxml/ChangeGood.fxml"));
        Scene scene = new Scene(fxmlLoader.load());
        Stage stage = new Stage();
        stage.setScene(scene);
        //设置窗口标题
        stage.setTitle("修改商品信息");
        //设置窗体不关闭不能使用其它窗体
        stage.initModality(Modality.APPLICATION_MODAL);
        //设置窗口大小不能改变
        stage.setResizable(false);
        stage.show();
    }

    public void toDeleteGood(ActionEvent actionEvent) {
        g = (Good) goodView.getSelectionModel().getSelectedItem();
        //使用系统确认框询问
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText("您确定要删除商品" + g.getgName() + "的全部信息吗？");
        // 显示对话框，并等待按钮返回
        Optional<ButtonType> result = alert.showAndWait();
        // 判断返回的按钮类型是确定还是取消，再据此分别进一步处理
        if (result.get() == ButtonType.OK) { // 单击了确定按钮OK
            new DeleteGoods().deleteGoods(g);
            loadGoodDate();//重新加载视图数据
        }
    }

    public void toFindStaff(ActionEvent actionEvent) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/example/teatea/fxml/FindStaff.fxml"));//定位界面文件
        Scene scene = new Scene(fxmlLoader.load());//加载界面到Scene场景对象
        Stage stage = new Stage();//创建Stage窗体对象
        stage.setScene(scene);//设置窗体的场景
        // stage.initStyle(StageStyle.TRANSPARENT);
        //设置窗口标题
        stage.setTitle("员工查询");
//        //设置窗体不关闭不能使用其它窗体
//        stage.initModality(Modality.APPLICATION_MODAL);
        //设置窗口大小不能改变
        stage.setResizable(false);
        stage.show();//显示窗体
    }

    public void toFindMember(ActionEvent actionEvent) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/example/teatea/fxml/FindMember.fxml"));//定位界面文件
        Scene scene = new Scene(fxmlLoader.load());//加载界面到Scene场景对象
        Stage stage = new Stage();//创建Stage窗体对象
        stage.setScene(scene);//设置窗体的场景
        // stage.initStyle(StageStyle.TRANSPARENT);
        //设置窗口标题
        stage.setTitle("会员查询");
//        //设置窗体不关闭不能使用其它窗体
//        stage.initModality(Modality.APPLICATION_MODAL);
        //设置窗口大小不能改变
        stage.setResizable(false);
        stage.show();//显示窗体
    }

    public void toFindGood(ActionEvent actionEvent) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/example/teatea/fxml/FindGoods.fxml"));//定位界面文件
        Scene scene = new Scene(fxmlLoader.load());//加载界面到Scene场景对象
        Stage stage = new Stage();//创建Stage窗体对象
        stage.setScene(scene);//设置窗体的场景
        // stage.initStyle(StageStyle.TRANSPARENT);
        //设置窗口标题
        stage.setTitle("商品查询");
//        //设置窗体不关闭不能使用其它窗体
//        stage.initModality(Modality.APPLICATION_MODAL);
        //设置窗口大小不能改变
        stage.setResizable(false);
        stage.show();//显示窗体
    }
}
